﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace OkTool.Http
{
   public class JsHelper
    {

        /// <summary>
        /// 执行js Eval方法 支持多线程
        /// </summary>
        /// <param name="reString">Js代码</param>
        /// <param name="para">方法名称</param>
        /// <param name="methodName">参数字符串(使用逗号分隔)</param>
        public string EvalMethod(string reString, string methodName, string para = "")
        {
            try
            {
                Type obj = Type.GetTypeFromProgID("ScriptControl");
                if (obj == null) return "";
                object scriptControl = Activator.CreateInstance(obj);
                obj.InvokeMember("Language", BindingFlags.SetProperty, null, scriptControl, new object[] { "JavaScript" });
                obj.InvokeMember("AddCode", BindingFlags.InvokeMethod, null, scriptControl, new object[] { reString });
                return obj.InvokeMember("Eval", BindingFlags.InvokeMethod, null, scriptControl, new object[] { string.Format("{0}({1})", methodName, para) }).ToString();//执行结果

            }
            catch (Exception ex)
            {
                string errorInfo = string.Format("执行JS出现错误:   \r\n 错误描述: {0} \r\n 错误原因: {1} \r\n 错误来源:{2}", ex.Message, ex.InnerException.Message, ex.InnerException.Source);//异常信息
                return errorInfo; //  ErrorInfo  异常信息
            }
        }
    }
}
